using System;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.ResourceManagement.AsyncOperations;
using Utils.Singleton;
using UnityEngine.AddressableAssets;

namespace AddressablesTool
{
    /// <summary>
    /// Addressables资源管理器，提供异步资源加载和场景管理功能
    /// </summary>
    public class AddressablesManager : MonoSingleton<AddressablesManager>
    {
        /// <summary>
        /// 是否不销毁单例对象
        /// </summary>
        protected override bool NotDestroyed => true;

        /// <summary>
        /// 是否已初始化完成
        /// </summary>
        public bool IsInitialized => _isInitialized;

        /// <summary>
        /// 是否自动初始化（静态设置）
        /// </summary>
        public static bool autoInitialize { set; get; }


        /// <summary>
        /// 资源管理器实例
        /// </summary>
        public AssetLoader AssetLoader { get; private set; }

        /// <summary>
        /// 场景管理器实例
        /// </summary>
        public SceneLoader SceneLoader { get; private set; }

        private bool _isInitialized;

        /// <summary>
        /// 初始化完成事件
        /// </summary>
        public event Action OnInitialized;


        /// <summary>
        /// 单例初始化方法
        /// </summary>
        protected override void Awake()
        {
            base.Awake();

            AssetLoader = new AssetLoader();
            SceneLoader = new SceneLoader();

            if (autoInitialize)
            {
                Initialize();
            }
        }

        /// <summary>
        /// 异步初始化Addressables系统
        /// </summary>
        /// <returns>初始化任务</returns>
        public async UniTask InitializeAsync()
        {
            if (_isInitialized)
            {
                return;
            }

            var handle = Addressables.InitializeAsync();
            await handle.ToUniTask();

            if (handle.Status != AsyncOperationStatus.Succeeded)
                throw new Exception("InitializeAsync failed");

            _isInitialized = true;
            AssetLoader.Initialize();
            SceneLoader.Initialize();
            OnInitialized?.Invoke();

            Debug.Log("Addressables Manager initialized");
        }


        /// <summary>
        /// 初始化Addressables系统
        /// </summary>
        public void Initialize()
        {
            if (_isInitialized)
                return;
            InitializeAsync().Forget();
        }

        /// <summary>
        /// 销毁时清理资源
        /// </summary>
        protected override void OnDestroy()
        {
            base.OnDestroy();
            AssetLoader?.ReleaseAllAssets();
            SceneLoader?.ReleaseAllScenes();
        }
    }
}